import time
from selenium.webdriver.common.by import By
from taobao_check.tools import click_by_js
from .base import BaseBrush


class DaZhou(BaseBrush):
    login_url = "http://qqq.dazhou12.com/Shop/Login/logon"
    index_url = "http://qqq.dazhou12.com/Shop/Index"
    check_url = "http://qqq.dazhou12.com/index.php?g=Shop&m=TaskManage&a=task_manage&flag=2"

    def __init__(self, config, tab):
        super().__init__("大舟", "dazhou", config, tab)

    def login(self):
        if self.browser.current_url != self.login_url:
            self.browser.get(self.login_url)

        self.enter_text((By.ID, "txtLoginName"), self.username)
        self.enter_text((By.ID, "txtPwd"), self.password)
        self.click_button((By.CSS_SELECTOR, "li.yhdl_2>a"))

        while self.browser.current_url != self.index_url:
            time.sleep(0.1)

        self.browser.get(self.check_url)

    def check_user(self):
        trs = self.find_elements((By.CSS_SELECTOR, "tbody>tr"), timeout=3)
        flag = False
        for tr in trs[1:]:
            tds = tr.find_elements_by_tag_name("td")
            if len(tds) < 7:
                continue
            buttons = tds[6].find_elements_by_tag_name("input")
            if len(buttons) < 3:
                continue

            username = tds[3].find_element_by_css_selector("p>span").get_attribute('textContent')
            username = username.split("：")[1].strip()
            self.print_log(f"当前待验买号为：【{username}】")

            start = time.time()
            result = self.check.check_user(username, self.print_log)

            self.print_log(f"验号结果为: {'通过' if result else '不通过'}. 用时: {time.time() - start:.2f}s")

            if not result:
                click_by_js(self.browser, buttons[0])
                # 点击确认
                iframe = self.find_element((By.CSS_SELECTOR, "iframe[scrolling='no']"))
                self.browser.switch_to.frame(iframe)
                self.click_button((By.CSS_SELECTOR, "input[id='btnSubmint']"))
                self.browser.switch_to.default_content()
            else:
                click_by_js(self.browser, buttons[2])
                self.click_button((By.CSS_SELECTOR, "li.sjzc_7_t>a"))
            flag = True
            break

        if not flag:
            self.print_log("没有买号.", debug=True)
            self.sleep(self.refresh_time)
            return False
        else:
            self.sleep(2)
            return True
